package com.webserver.controller;

import com.webserver.core.ClientHandler;
import com.webserver.entity.User;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.URISyntaxException;

/**
 * MVC模型
 * M:model
 * V:view
 * C:controller
 *
 * 处理与用户相关的业务操作
 */
public class UserController {
    private static File staticDir;
    private static File USER_DIR = new File("./users");//实例化目录
    static{
        if(!USER_DIR.exists()){//如果目录不存则创建目录
            USER_DIR.mkdir();
        }
        try {
            staticDir=new File(
                    ClientHandler.class.getClassLoader().getResource(
                            "./static"
                    ).toURI()
            );
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
    /**
     * 处理用户注册
     * @param request
     * @param response
     */
    public void register(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始处理用户注册");
        //1、获取用户表单提交上来的数据
        String username=request.getParameters("username");
        String password=request.getParameters("password");
        String nickname=request.getParameters("nickname");
        String ageStr=request.getParameters("age");
        System.out.println(username+","+password+","+nickname+","+ageStr);
        System.out.println("处理用户注册完毕");
        //2、将用户信息以一个user实例表示并序列化到文件中
        int age = Integer.parseInt(ageStr);
        User user = new User(username,password,nickname,age);
        //将该用户信息以用户名.obj的实行保存到users目录中
        File userFile = new File(USER_DIR,username+".obj");
        try(
            FileOutputStream fos = new FileOutputStream(userFile);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            )
        {
            oos.writeObject(user);
            //注册成功
            File file = new File(staticDir,"/myweb/reg_success.html");
            response.setContentFile(file);
        }
        catch(IOException e){

        }
    }
}
